package com.qt.manager;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/9/17 23:28
 */
@Component
@Slf4j(topic = "qtoj")
public class EmailManager {

    @Autowired
    private TemplateEngine templateEngine;

    public JavaMailSenderImpl getMailSender() {

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost("smtp.qq.com");
        sender.setPort(587);
        sender.setDefaultEncoding("UTF-8");
        sender.setUsername("3219857569@qq.com");
        sender.setPassword("ukdymwxfgufcdcib");


        Properties p = new Properties();
        p.setProperty("mail.smtp.ssl.enable"," false");
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.starttls.enable", "webConfig.getEmailSsl().toString()");
        sender.setJavaMailProperties(p);
        return sender;
    }

    public void sendRegisterCode(String email, String code) {
        DateTime expireTime = DateUtil.offsetMinute(new Date(), 10);
        JavaMailSenderImpl mailSender = getMailSender();
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置渲染到html页面对应的值
            Context context = new Context();
            context.setVariable("CODE", code);
            context.setVariable("EXPIRE_TIME", expireTime.toString());

            //利用模板引擎加载html文件进行渲染并生成对应的字符串
            String emailContent = templateEngine.process("emailTemplate_registerCode", context);

            // 设置邮件标题
            mimeMessageHelper.setSubject( "注册邮件");
            mimeMessageHelper.setText(emailContent, true);
            // 收件人
            mimeMessageHelper.setTo(email);
            // 发送人
            mimeMessageHelper.setFrom("3219857569@qq.com");

            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("用户注册的邮件任务发生异常------------>{}", e.getMessage());
        }

    }

    /**
     * 给指定邮箱发送重置密码消息链接
     * @param username
     * @param code
     * @param
     */
     @Async
    public void sendResetPassword(String username, String code, String email) {

    }
}
